package models

import (
	"github.com/gomodule/redigo/redis"
	"strconv"
	"time"
)

type Blog struct {
	Id            int       `json:"id" orm:"pk;auto"`
	BlogName      string    `json:"blog_name"`
	BlogContent   string    `json:"blog_content" orm:"type(text)"`
	BlogDate      time.Time `json:"blog_date"`
	BlogState     int8      `json:"blog_state"`
	BlogTop       int8      `json:"blog_top"`
	BlogPicture   string    `json:"blog_picture"`
	BlogShowWords string    `json:"blog_show_words"`
	Types         []*Type   `json:"types" orm:"reverse(many)"`
	Labels        []*Label  `json:"labels" orm:"reverse(many)"`
	Uid           *User     `json:"uid" orm:"rel(fk)"`
}

func (b *Blog) TableName() string {
	return TableName("blog")
}

// GetViews 获取该博客的浏览量
func (b *Blog) GetViews(id int) (n int, err error) {
	get := pool.Get()
	blogViews := "blogViews:" + strconv.Itoa(id)
	do, err := get.Do("EXISTS", blogViews)
	if do == int64(1) {
		n, err = redis.Int(get.Do("get", blogViews))
		if err != nil {
			return
		}
	}
	return n, err
}

// GetAllViews 获取总的浏览量
func (b *Blog) GetAllViews() (n int, err error) {
	get := pool.Get()
	allBlogViews := "allBlogViews"
	doAll, _ := get.Do("EXISTS", allBlogViews)
	if doAll == int64(1) {
		n, err = redis.Int(get.Do("Get", allBlogViews))
	}
	return
}

// AddViews 增加该博客的浏览量
func (b *Blog) AddViews(id int) (err error) {
	get := pool.Get()
	blogViews := "blogViews:" + strconv.Itoa(id)
	do, _ := get.Do("EXISTS", blogViews)
	if do == int64(1) {
		_, err = get.Do("incr", blogViews)
	} else {
		_, err = get.Do("set", blogViews, 1)
	}
	return err
}

// AddAllViews 增加所有博客的浏览量
func (b *Blog) AddAllViews() (err error) {
	get := pool.Get()
	allBlogViews := "allBlogViews"
	doAll, _ := get.Do("EXISTS", allBlogViews)
	if doAll == int64(1) {
		_, err = get.Do("incr", allBlogViews)
	} else {
		_, err = get.Do("set", allBlogViews, 1)
	}
	return
}

// AddDayViews 增加博客日浏览量
func (b *Blog) AddDayViews() (err error) {
	get := pool.Get()
	viewsInADay := "blogViews:" + time.Unix(time.Now().Unix(), 0).String()[:10]
	doADay, err := get.Do("EXISTS", viewsInADay)
	if doADay == int64(1) {
		_, err = get.Do("incr", viewsInADay)
	} else {
		_, err = get.Do("set", viewsInADay, 1)
	}
	return
}
